import { Effect, Reducer } from 'umi';

export interface IGlobalState {
  user: {
    name: string;
    age: number;
    like: string[];
  };
}

export interface IGlobalModel {
  namespace: 'global';
  state: IGlobalState;
  effects: {
    login: Effect;
  };
  reducers: {
    save: Reducer<IGlobalState>;
  };
}

const GlobalModel: IGlobalModel = {
  namespace: 'global',
  state: {
    user: {
      name: '张三',
      age: 18,
      like: ['吃饭', '睡觉'],
    },
  },
  effects: {
    *login({ type, payload }, { call, put }) {
      const data = yield login();
      yield put({
        type: 'save',
        payload: {
          user: data,
        },
      });
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default GlobalModel;

const login = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        name: '李四',
        age: 21,
        like: ['看书', '写字'],
      });
    }, 2000);
  });
};
